package com.yesjpt.serv.impl;

import com.alibaba.fastjson.JSONObject;
import com.yesjpt.dao.UserDao;
import com.yesjpt.domain.User;
import com.yesjpt.serv.UserServ;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServImpl implements UserServ {
    @Autowired
    private UserDao dao; //本来就在User下面，所以不要用userDao了，要调用其它DAO的时候再加前缀

    //查看所有
    @Override
    public List<User> findAll() {
        return dao.findAll();
    }

    //更新（修改用户昵称）
    @Override
    @Transactional
    public JSONObject updateNickname(String id, String nickName) {
        System.out.println(new Throwable().getStackTrace()[0]);
        JSONObject o = new JSONObject();
        o.put("success", true);
        try {
            dao.updateNickname(id, nickName);
            o.put("message", "更新操作成功");
            return o;
        } catch (Exception e) {
            System.out.println(new Throwable().getStackTrace()[0] + "异常：" + e);
            o.put("success", false);
            o.put("message", "更新操作异常：" + e);
            return o;
        }
    }

    //删除一个用户
    @Override
    @Transactional
    public JSONObject delete(String id) {
        System.out.println(new Throwable().getStackTrace()[0]);
        JSONObject o = new JSONObject();
        Integer r = dao.delete(id);
        if (r > 0) {
            o.put("success", true);
            o.put("message", "删除操作成功");
        } else {
            o.put("success", false);
            o.put("message", "删除操作失败，没有这个记录，id = " + id);
        }
        return o;
    }

    //添加用户
    @Override
    @Transactional
    public JSONObject add(User vo) {
        System.out.println(new Throwable().getStackTrace()[0]);
        JSONObject o = new JSONObject();
        o.put("success", true);
        System.out.println(vo);
        try {
            dao.add(vo);
            o.put("message", "新增操作成功");
        } catch (Exception e) {
            o.put("success", false);
            o.put("message", "新增操作异常：" + e);
        }
        return o;
    }
}
